package com.example.routeplansystem.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @Author: Lunaticer
 * @Create: 2022-02-10 19:08
 * @Tip: Keeping the eyes of the prize !
 * @Description: JWT Token令牌工具类
 */
public class JWTUtil {

    //JWT Token密钥：
    private static final String SING = "@#$$%^&*()_+";

    //生成token header、payload、sing：
    public static String getToken(Map<String,Object> map){

        //设置Token过期时间：
        Calendar instance = Calendar.getInstance();
        //设置默认7天过期
        instance.add(Calendar.DATE,7);
        //创建jwt Builder：
        JWTCreator.Builder builder = JWT.create();

        //payload（向Token中存入信息）：
        map.forEach((k,v)->{
            builder.withClaim(k,(String)v);
        });

        String token = builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SING));

        return token;
    }

     //验证token 合法性：
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    //获取token信息：
    public static DecodedJWT getTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        return verify;
    }
}
